<?php
/*
Plugin Name: VTP projects
Plugin URI: http://www.dudyland.sk
Description: VTP projects
Version: 0.1
Author: Peter Turza, Pavol Martiniak
Author URI: http://www.dudyland.sk
*/
?>
<?php
class VTPProjects {

    private $wpdb;
    // obmedzenia dlzky textu a perexu
    private static $minPerexLength = 0;
    private static $maxPerexLength = 10000;
    private static $minTextLength = 0;
    private static $maxTextLength = 10000;
    
    function __construct() {
        global $wpdb;
        $this->wpdb = $wpdb;
        add_action('admin_menu', array(&$this,'projectsMenu'));
        wp_register_script('jquery-validate', get_bloginfo(url).'/wp-includes/js/validate/jquery.validate.js');
        wp_register_script('myscript', get_bloginfo(url).'/wp-includes/js/validate/myscript.js');
        
        // YUI editor
        wp_register_style('yui-skin-sam', '/wp-includes/js/yui/build/assets/skins/sam/skin.css');
        wp_register_script('yahoo-dom-event', get_bloginfo(url).'/wp-includes/js/yui/build/yahoo-dom-event/yahoo-dom-event.js'); 
        wp_register_script('element', get_bloginfo(url).'/wp-includes/js/yui/build/element/element-min.js'); 
        wp_register_script('container_core', get_bloginfo(url).'/wp-includes/js/yui/build/container/container_core-min.js'); 
        wp_register_script('menu', get_bloginfo(url).'/wp-includes/js/yui/build/menu/menu-min.js'); 
        wp_register_script('button', get_bloginfo(url).'/wp-includes/js/yui/build/button/button-min.js'); 
        wp_register_script('editor2', get_bloginfo(url).'/wp-includes/js/yui/build/editor/editor-min.js'); 
    }

    function projectsMenu() {
        add_menu_page('VTP Projects', 'Projekty', 'edit_pages', 'projectsMenu', array(&$this, 'listAll'));
        add_submenu_page('projectsMenu', 'Pridať nový projekt', 'Pridať nový projekt', 'edit_pages', 'addProject', array(&$this, 'addProject'));
        wp_enqueue_script('jquery-validate');
        wp_enqueue_script('myscript');
        
        wp_enqueue_style('yui-skin-sam');
        wp_enqueue_script('yahoo-dom-event');
        wp_enqueue_script('element');
        wp_enqueue_script('container_core');
        wp_enqueue_script('menu');
        wp_enqueue_script('button');        
        wp_enqueue_script('editor2');       
    }
    
    /**
    * @desc Funkcia sluzi ako navigacia medzi jednotlivymi metodami.
    */    
    function listAll() {
        
        if ($_GET['action'] == 'edit') { // editacia
            $this->editProject($_GET['id']);
        } else if ($_GET['action'] == 'delete') { // mazanie zaznamu
            $this->deleteProject($_GET['id']);
        } else {
            $this->listing();
        }
    }
    
    /**
    * @desc Zobrazi formular a pridava zaznam do DB.
    */
    function addProject() {
        if (!isset($_POST['submitted'])) { // show form
            echo VTPProjects::initYuiEditor();
            
            echo '<div id="wrap">';
            echo '<h3>Pridať nový projekt</h3>';
            
            echo '<form action="'.$_SERVER['REQUEST_URI'].'" id="addProject" method="post" enctype="multipart/form-data">';
            echo '<table class="form-table">';
            echo '<tr><td><label for="projectName">Názov projektu: *</label></td>';
            echo '<td><input type="text" name="projectName" id="projectName" value="" /></td></tr>';
            echo '<tr><td><label for="projectAbbrevation">Skratka projektu: </label></td>';
            echo '<td><input type="text" name="projectAbbrevation" value="" /></td></tr>';
            echo '<tr><td><label for="projectCategory1">Kategória 1: *</label></td><td>';
            wp_dropdown_categories(array('child_of'=>10, 'hide_empty'=>0, 'name'=>'projectCategory1'));
            echo '</td></tr>';
            echo '<tr><td><label for="projectCategory2">Kategória 2: *</label></td><td>';
            wp_dropdown_categories(array('child_of'=>9, 'hide_empty'=>0, 'name'=>'projectCategory2'));
            echo '</td></tr>';
            echo '<tr><td><label for="projectLogo">Logo projektu: *</label></td>';
            echo '<td><input type="file" name="projectLogo" id="projectLogo" /></td></tr>';
            echo '<tr><td><label for="projectEmail">Kontaktný email: *</label></td>';
            echo '<td><input type="text" name="projectEmail" id="projectEmail" value="" /></td></tr>';
            echo '<tr><td><label for="projectPerex">Anotácia: *</label></td>';
            echo '<td><textarea name="projectPerex" id="projectPerex" cols="50" rows="5" ></textarea></td></tr>';
            echo '<tr><td><label for="projectText">Text: </label></td>';
            echo '<td><textarea name="projectText" id="projectText" ></textarea></td></tr>';
            echo '<tr><td><label for="projectLink1">Súvisiaci link 1: </label></td>';
            echo '<td><input type="text" name="projectLink1" id="projectLink1" value="" class="url" /></td></tr>';
            echo '<tr><td><label for="projectLink2">Súvisiaci link 2: </label></td>';
            echo '<td><input type="text" name="projectLink2" id="projectLink2" value="" class="url" /></td></tr>';
            echo '<tr><td><label for="projectLink3">Súvisiaci link 3: </label></td>';
            echo '<td><input type="text" name="projectLink3" id="projectLink3" value="" class="url" /></td></tr>';
            echo '<tr><td><label for="projectGallery">Galéria: </label></td>';
            echo '<td><input type="text" name="projectGallery" id="projectGallery" class="url" value="" /></td></tr>';
            
            echo '<input type="hidden" name="submitted" value="true">';
            
            echo '<tr><td></td><td><input name="submit" type="submit" id="submit" value="Pridať projekt" /></td></tr>';
            echo '</table>';
            echo '</form>';
            echo '<script type="text/javascript">
                    jQuery("#addProject").validate({
                        rules: {
                            projectName: {required: true},
                            projectLogo: {required: true, accept: "jpe?g|gif|png"},
                            projectEmail: {required: true, email: true},
                            projectPerex: {required: true, minlength: '.VTPProjects::$minPerexLength.', maxlength: '.VTPProjects::$maxPerexLength.'},
                            projectText: {minlength: '.VTPProjects::$minTextLength.', maxlength: '.VTPProjects::$maxTextLength.'},
                            projectLink1: {url: true},
                            projectLink2: {url: true},
                            projectLink3: {url: true},
                            projectGallery: {url: true}
                        }
                    });
                    
                    jQuery("#addProject").submit(function() {
                        myEditor.saveHTML();
                    });                    
                    </script>';
            echo '</div>';
        } else {
            $category1 = $_POST['projectCategory1'];
            $logo = $_FILES['projectLogo']['name'];
            $name = $_POST['projectName'];
            $abbrevation = $_POST['projectAbbrevation'];
            $email = $_POST['projectEmail'];
            $perex = $_POST['projectPerex'];
            $text = $_POST['projectText'];
            $link1 = $_POST['projectLink1'];
            $link2 = $_POST['projectLink2'];
            $link3 = $_POST['projectLink3'];
            $gallery = $_POST['projectGallery'];
            $category2 = $_POST['projectCategory2'];

            // kontrola, ci uz je zaznam v DB - kvoli duplicite pri refreshnuti po vlozeni
            $checkRow = $this->wpdb->get_row("SELECT * FROM wp_projects WHERE category1=$category1 AND logo='$logo'
            AND name='$name' AND abbrevation='$abbrevation' AND email='$email' AND perex='$perex' AND text='$text' 
            AND link1='$link1' AND link2='$link2' AND link3='$link3' AND gallery='$gallery' AND category2=$category2");
            
            if ($checkRow == null) {
                // Create post object
                $projectPost = array();
                $projectPost['post_title'] = $name.($abbrevation==''?'':(' ('.$abbrevation.')'));
                $projectPost['post_excerpt'] = str_replace("\n"," ",str_replace("\r"," ",$perex));
                $projectPost['post_content'] = str_replace("\n"," ",str_replace("\r"," ",$text));
                $projectPost['post_status'] = 'publish';
                $projectPost['post_category'] = array($category1, $category2);

                // Insert the post into the database
                $postId = wp_insert_post( $projectPost );

                update_post_meta($postId, 'project', 1);
                update_post_meta($postId, 'email', $email);
                update_post_meta($postId, 'link1', $link1);
                update_post_meta($postId, 'link2', $link2);
                update_post_meta($postId, 'link3', $link3);
                update_post_meta($postId, 'gallery', $gallery);

                $data = array('id' => 'NULL', 'name' => $name, 'category1' => $category1, 'logo' => $logo, 
                    'abbrevation' => $abbrevation, 'email' => $email, 'perex' => $perex, 'text' => $text, 
                    'link1' => $link1, 'link2' => $link2, 'link3' => $link3, 'gallery' => $gallery, 
                    'category2' => $category2, 'post_id'=>$postId);
                    
                // vloz do DB
                $this->wpdb->insert('wp_projects', $data);
                $lastId = $this->wpdb->insert_id;
                
                // presun foto do upload priecinku
                $upload = VTPProjects::my_wp_upload_bits($_FILES["projectLogo"]["name"], null, file_get_contents($_FILES["projectLogo"]["tmp_name"]), null, '/projects/'.$lastId );

                $attachment = array(
                    'post_title'=>$_FILES["projectLogo"]["name"],
                    'post_content'=>'',
                    'post_status' => 'publish',
                    'post_mime_type'=>$_FILES["projectLogo"]['type']);
                $filename = $upload['file'];
                $attachId = wp_insert_attachment( $attachment, $filename, $postId );
                $attachData = wp_generate_attachment_metadata( $attachId, $filename );
                wp_update_attachment_metadata( $attachId,  $attachData );
                update_post_meta($postId, 'logo', $attachId);
                unset($_POST['submitted']);
            }
            // ak vsetko prebehlo, presmeruj na listAll
            unset($_POST['submitted']);
            unset($_GET['action']);
            $this->listAll();            
        }
    }
    
    /**
    * @desc Formular na editaciu zaznamov.
    */
    private function editProject($id) {
        if (!isset($_POST['submitted'])) { // show form
            echo VTPProjects::initYuiEditor();
        
            $project = $this->wpdb->get_row('SELECT * FROM wp_projects WHERE id = '.$id);
            
            echo '<div id="wrap">';
            echo '<h2>Upraviť projekt "'.$project->name.'"</h2>';
            
            echo '<form action="'.$_SERVER['REQUEST_URI'].'" id="editProject" method="post" enctype="multipart/form-data">';
            echo '<table class="form-table">';
            echo '<tr><td><label for="projectName">Názov projektu: </label></td>';
            echo '<td><input type="text" name="projectName" id="projectName" class="required" value="'.$project->name.'" /></td></tr>';
            echo '<tr><td><label for="projectAbbrevation">Skratka: </label></td>';
            echo '<td><input type="text" name="projectAbbrevation" id="projectAbbrevation" value="'.$project->abbrevation.'" /></td></tr>';
            echo '<tr><td><label for="projectCategory1">Kategória 1: </label></td><td>';
            wp_dropdown_categories(array('child_of'=>10, 'hide_empty'=>0, 'name'=>'projectCategory1', 'selected'=>$project->category1));
            echo '</td></tr>';
            echo '<tr><td><label for="projectCategory2">Kategória 2: </label></td><td>';
            wp_dropdown_categories(array('child_of'=>9, 'hide_empty'=>0, 'name'=>'projectCategory2', 'selected'=>$project->category2));
            echo '</td></tr>';
            jr_post_image($project->post_id);
            echo '<tr><td><label for="projectLogo">Logo projektu: </label></td>';
            echo '<td><input type="file" name="projectLogo" id="projectLogo" accept="jpe?g|gif|png" /></td></tr>';
            echo '<tr><td><label for="projectEmail">Kontaktný email: </label></td>';
            echo '<td><input type="text" name="projectEmail" id="projectEmail" value="'.$project->email.'" /></td></tr>';
            echo '<tr><td><label for="projectPerex">Anotácia: </label></td>';
            echo '<td><textarea name="projectPerex" id="projectPerex" cols="50" rows="5">'.$project->perex.'</textarea></td></tr>';
            echo '<tr><td><label for="projectText">Text: </label></td>';
            echo '<td><textarea name="projectText" id="projectText" >'.$project->text.'</textarea></td></tr>';
            echo '<tr><td><label for="projectLink1">Súvisiaci link 1: </label></td>';
            echo '<td><input type="text" name="projectLink1" id="projectLink1" value="'.$project->link1.'" /></td></tr>';
            echo '<tr><td><label for="projectLink2">Súvisiaci link 2: </label></td>';
            echo '<td><input type="text" name="projectLink2" id="projectLink2" value="'.$project->link2.'" /></td></tr>';
            echo '<tr><td><label for="projectLink3">Súvisiaci link 3: </label></td>';
            echo '<td><input type="text" name="projectLink3" id="projectLink3" value="'.$project->link3.'" /></td></tr>';
            echo '<tr><td><label for="projectGallery">Galéria: </label></td>';
            echo '<td><input type="text" name="projectGallery" id="projectGallery" value="'.$project->gallery.'"/></td></tr>';

            echo '<input type="hidden" name="postId" value="'.$project->post_id.'">';
            echo '<input type="hidden" name="submitted" value="true">';
            
            echo '<tr><td></td><td><input type="submit" id="submit" value="Upraviť projekt" /></td></tr>';
            echo '</table>';
            echo '</form>';
            echo '<script type="text/javascript">
                    jQuery("#editProject").validate({
                        rules: {
                            projectName: {required: true},
                            projectLogo: {accept: "jpe?g|gif|png"},
                            projectEmail: {required: true, email: true},
                            projectPerex: {required: true, minlength: '.VTPProjects::$minPerexLength.', maxlength: '.VTPProjects::$maxPerexLength.'},
                            projectText: {minlength: '.VTPProjects::$minTextLength.', maxlength: '.VTPProjects::$maxTextLength.'},
                            projectLink1: {url: true},
                            projectLink2: {url: true},
                            projectLink3: {url: true},
                            projectGallery: {url: true}
                        }
                    });
                    
                    jQuery("#editProject").submit(function() {
                        myEditor.saveHTML();
                    });
                    </script>';
            echo '</div>';
        } else {
            $category1 = $_POST['projectCategory1'];
            $name = $_POST['projectName'];
            $abbrevation = $_POST['projectAbbrevation'];
            $email = $_POST['projectEmail'];
            $perex = $_POST['projectPerex'];
            $text = $_POST['projectText'];
            $link1 = $_POST['projectLink1'];
            $link2 = $_POST['projectLink2'];
            $link3 = $_POST['projectLink3'];
            $gallery = $_POST['projectGallery'];
            $category2 = $_POST['projectCategory2'];
            $logo = $_FILES['projectLogo']['name'];
            
            // Create post object
            $projectPost = array();
            $projectPost['ID'] = $_POST['postId'];
            $projectPost['post_title'] = $name.($abbrevation==''?'':(' ('.$abbrevation.')'));
            $projectPost['post_excerpt'] = str_replace("\n"," ",str_replace("\r"," ",$perex));
            $projectPost['post_content'] = str_replace("\n"," ",str_replace("\r"," ",$text));
            $projectPost['post_status'] = 'publish';
            $projectPost['post_category'] = array($category1, $category2);

            // Insert the post into the database
            $postId = wp_update_post( $projectPost );

            update_post_meta($postId, 'email', $email);
            update_post_meta($postId, 'link1', $link1);
            update_post_meta($postId, 'link2', $link2);
            update_post_meta($postId, 'link3', $link3);
            update_post_meta($postId, 'gallery', $gallery);

            $data = array('name' => $name, 'category1' => $category1, 'abbrevation' => $abbrevation, 
                'email' => $email, 'perex' => $perex, 'text' => $text, 'category2' => $category2,
                'link1' => $link1, 'link2' => $link2, 'link3' => $link3, 'gallery' => $gallery,
                'post_id' => $postId);
                            
            if ($logo != '') { // ak bola zmenena fotka
                $data['logo'] = $logo;
            }
                
            // vloz do DB
            $this->wpdb->update('wp_projects', $data, array( 'id' => $id ));
            
            // presun foto do upload priecinku, ak bola zmenena fotka
            if ($logo != '') {
                wp_delete_attachment(get_post_meta($postId, 'logo', true));
                $upload = VTPProjects::my_wp_upload_bits($_FILES["projectLogo"]["name"], null, file_get_contents($_FILES["projectLogo"]["tmp_name"]), null, '/projects/'.$id );
                $attachment = array(
                    'post_title'=>$_FILES["projectLogo"]["name"],
                    'post_content'=>'',
                    'post_status' => 'publish',
                    'post_mime_type'=>$_FILES["projectLogo"]['type']);
                $filename = $upload['file'];
                $attachId = wp_insert_attachment( $attachment, $filename, $postId );
                $attachData = wp_generate_attachment_metadata( $attachId, $filename );
                wp_update_attachment_metadata( $attachId,  $attachData );
                update_post_meta($postId, 'logo', $attachId);
            }
            
            unset($_POST['submitted']);
            unset($_GET['action']);
            $this->listAll();
        }
    }

    /**
    * @desc Zmaze zaznam a presunie uzivatela spat na listing.
    */
    function deleteProject($id) {
        $project = $this->wpdb->get_row('SELECT * FROM wp_projects WHERE id = '.$id);
        // vymazanie loga, aj suboru z disku
        wp_delete_attachment(get_post_meta($project->post_id, 'logo', true));
        // vymazanie pridruzeneho postu
        wp_delete_post($project->post_id);
        $this->wpdb->query('DELETE FROM wp_projects WHERE id = '.$id);
        
        // po uspesnom zmazni chod spat na listing
        unset($_GET['action']);
        unset($_GET['id']);        
        $this->listAll();
    }
    
    /**
    * @desc Listing partnerov.
    */
    function listing() {
        echo '<div id="wrap">';
        echo '<h2>Zoznam projektov</h2>'; // zoznam projektov
        $result = $this->wpdb->get_results("SELECT * FROM wp_projects");
        echo '<table class="form-table">';
        foreach ($result as $r) {
            echo '<tr><td><a href="?page=projectsMenu&action=edit&id='.$r->id.'">'.$r->name.'</a></td><td><a href="?page=projectsMenu&action=delete&id='.$r->id.'" onClick="return confirmDelete(\''.$r->name.'\');">Zmazať</a></td></tr>';
        }
        echo '</table>';
        echo '<div>';
    }
        
    /**
    * @desc Vrati inicializaciu YUI editora.
    */
    private static function initYuiEditor() {
        $str = "<script type=\"text/javascript\">
                    var myEditor = new YAHOO.widget.Editor('projectText', {
                        height: '200px',
                        width: '550px',
                        dompath: false,
                        animate: true,
                        toolbar: {
                            collapse: true,
                            titlebar: '',
                            draggable: false,
                            buttonType: 'advanced',
                            buttons: [
                                { group: 'fontstyle', label: 'Font Size',
                                    buttons: [
                                        { type: 'spin', label: '13', value: 'fontsize', range: [ 9, 75 ], disabled: true }
                                    ]
                                },
                                { type: 'separator' },
                                { group: 'textstyle', label: 'Font Style',
                                    buttons: [
                                        { type: 'push', label: 'Bold CTRL + SHIFT + B', value: 'bold' },
                                        { type: 'push', label: 'Italic CTRL + SHIFT + I', value: 'italic' },
                                        { type: 'push', label: 'Underline CTRL + SHIFT + U', value: 'underline' },
                                        { type: 'separator' },
                                        { type: 'push', label: 'Subscript', value: 'subscript', disabled: true },
                                        { type: 'push', label: 'Superscript', value: 'superscript', disabled: true },
                                        { type: 'separator' },
                                        { type: 'color', label: 'Font Color', value: 'forecolor', disabled: true },
                                        { type: 'color', label: 'Background Color', value: 'backcolor', disabled: true },
                                        { type: 'separator' },
                                        { type: 'push', label: 'Remove Formatting', value: 'removeformat', disabled: true },
                                        { type: 'push', label: 'Show/Hide Hidden Elements', value: 'hiddenelements' }
                                    ]
                                },
                                { type: 'separator' },
                                { group: 'alignment', label: 'Alignment',
                                    buttons: [
                                        { type: 'push', label: 'Align Left CTRL + SHIFT + [', value: 'justifyleft' },
                                        { type: 'push', label: 'Align Center CTRL + SHIFT + |', value: 'justifycenter' },
                                        { type: 'push', label: 'Align Right CTRL + SHIFT + ]', value: 'justifyright' },
                                        { type: 'push', label: 'Justify', value: 'justifyfull' }
                                    ]
                                },
                                { type: 'separator' },
                                { group: 'indentlist', label: 'Lists',
                                    buttons: [
                                        { type: 'push', label: 'Indent', value: 'indent', disabled: true },
                                        { type: 'push', label: 'Outdent', value: 'outdent', disabled: true },
                                        { type: 'push', label: 'Create an Unordered List', value: 'insertunorderedlist' },
                                        { type: 'push', label: 'Create an Ordered List', value: 'insertorderedlist' }
                                    ]
                                },
                                { type: 'separator' },
                                { group: 'insertitem', label: 'Insert Item',
                                    buttons: [
                                        { type: 'push', label: 'HTML Link CTRL + SHIFT + L', value: 'createlink', disabled: true }
                                    ]
                                }
                            ]

                        }
                    });
                    myEditor.render();
                    </script>";
        return $str;
    }    
    
    /**
    * @desc Vrati zoznam projektov
    */
    function getProjects($cat1, $cat2) {
        $projects = $this->wpdb->get_results('SELECT * FROM wp_projects WHERE category1 = '.$cat1.'
            AND category2 = '.$cat2);
        return $projects;
    }
    
    /**
    * @desc Vrati projekt podla post_id
    */
    function getProjectByPostId($postId) {
        $project = $this->wpdb->get_row('SELECT * FROM wp_projects WHERE post_id = '.$postId);
        return $project;
    }
    
    /**
    * @desc Upravena funkcia pre upload suboru z functions.php.
    */
    private static function my_wp_upload_bits( $name, $deprecated, $bits, $time = null, $subFolder = '' ) {
        if ( empty( $name ) )
            return array( 'error' => __( 'Empty filename' ) );

        $wp_filetype = wp_check_filetype( $name );
        if ( !$wp_filetype['ext'] )
            return array( 'error' => __( 'Invalid file type' ) );

        $upload = wp_upload_dir( $time );

        if ( $upload['error'] !== false )
            return $upload;

        $filename = wp_unique_filename( $upload['path'], $name );

        $new_file = $upload['basedir'] . $subFolder . "/$filename";
        if ( ! wp_mkdir_p( dirname( $new_file ) ) ) {
            $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), dirname( $new_file ) );
            return array( 'error' => $message );
        }

        $ifp = @ fopen( $new_file, 'wb' );
        if ( ! $ifp )
            return array( 'error' => sprintf( __( 'Could not write file %s' ), $new_file ) );

        @fwrite( $ifp, $bits );
        fclose( $ifp );
        // Set correct file permissions
        $stat = @ stat( dirname( $new_file ) );
        $perms = $stat['mode'] & 0007777;
        $perms = $perms & 0000666;
        @ chmod( $new_file, $perms );

        // Compute the URL
        $url = $upload['url'] . "/$filename";

        return array( 'file' => $new_file, 'url' => $url, 'error' => false );
    }
    
}

add_action('plugins_loaded', create_function('','global $vtpProjects; $vtpProjects = new VTPProjects();'));

?>